﻿#include "DataTypeDlg.h"
#include "Application.h"
#include <qtablewidget.h>
#include "cfg.h"
#include "Note.h"

DataTypeDlg::DataTypeDlg() : BaseDlg{ nullptr,"数据类型维护" }
{
	ui.setupUi(&content_view);
	this->base_ui.content->addWidget(&content_view);
	auto& types = Application::Instance().cfg.DataTypes();
	int row{};
	for(auto& item : types)
	{
		if(item.first != invalid_value_id)
		{
			static QIcon delete_icon{":/menu/delete"};
			this->ui.tableWidget->setRowCount(row + 1);
			this->ui.tableWidget->setItem(row, 0, new QTableWidgetItem(QString::number(item.first)));
			this->ui.tableWidget->setItem(row, 1, new QTableWidgetItem(item.second.c_str()));
			this->ui.tableWidget->setItem(row, 2, new QTableWidgetItem(delete_icon, ""));
			++row;
		}
	}

	connect(ui.pushButton, &QPushButton::clicked, this, &DataTypeDlg::slot_add_row);
}

DataTypeDlg::~DataTypeDlg()
{}

void DataTypeDlg::slot_add_row()
{
	auto& types = Application::Instance().cfg.DataTypes();
	auto key = static_cast<unsigned int>(ui.spinBox->value());
	if(ui.lineEdit->text().isEmpty())
	{
		Note nt{ "值不能为空" };
		nt.showDialog();
		return;
	}
	if(types.find(key) == types.end())
	{
		types[key] = ui.lineEdit->text().toStdString();
		Application::Instance().cfg.chg();
		auto row = this->ui.tableWidget->rowCount();
		this->ui.tableWidget->setRowCount(this->ui.tableWidget->rowCount() + 1);
		this->ui.tableWidget->setItem(row, 0, new QTableWidgetItem(QString::number(key)));
		this->ui.tableWidget->setItem(row, 1, new QTableWidgetItem(ui.lineEdit->text()));
		this->ui.tableWidget->setItem(row, 2, new QTableWidgetItem(QIcon{":/menu/delete"}, ""));
	}
	else
	{
		Note nt{ "键值冲突" };
		nt.showDialog();
	}
}
